<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in">
      <div class="cornerComment-in-title">
        <span>新增请假单</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody">
        <el-alert
            title="1、天数按半天计算。2、不满一小时按一小时计算。园区放假日期不计算请假天数。"
            type="warning"
            :closable="false">
        </el-alert>
        <el-form :model="infoForm" label-width="120px" ref="editForm" class="form-box">
          <el-form-item label="请假类型：">
<!--            <el-radio-group v-model="infoForm.cate_id" @change="typeChangeFn()">-->
<!--              <el-radio :label="item.id" v-for="item in tabList" :key="item.id">{{ item.name }}</el-radio>-->
<!--            </el-radio-group>-->
            <el-select v-model="infoForm.cate_id" placeholder="请选择" size="small" @change="changeTime()">
              <el-option
                  v-for="item in tabList" :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间：" v-if="loadingFrom">
            <div class="form-list-line">
              <el-date-picker type="date"
                              size="small"
                              @change="getTimeFn"
                              placeholder="选择开始时间"
                              v-model="infoForm.start_time"
                              value-format="yyyy-MM-dd"
                              class="w-100 mr-10"></el-date-picker>
              <div class="form-list-line-right">


                <el-radio-group v-model="timeoption.start" v-if="time_type==1" @change="getTimeFn">
                  <el-radio :label="item.id" v-for="item in timeType" :key="item.id">{{ item.name }}</el-radio>
                </el-radio-group>
                <el-time-picker
                    @change="typeChangeFn()"
                    class="w-80"
                    v-else
                    size="small"
                    v-model="start_hours"
                    format="HH:mm"
                    value-format="HH:mm"
                    :picker-options="{
    selectableRange: '06:00:00 - 23:00:00'
  }"
                    placeholder="选择时间">
                </el-time-picker>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="结束时间：" v-if="loadingFrom">
            <div class="form-list-line">
              <el-date-picker type="date"
                              size="small"
                              @change="getTimeFn"
                              placeholder="选择结束时间"
                              v-model="infoForm.end_time"
                              value-format="yyyy-MM-dd"
                              class="w-100 mr-10"></el-date-picker>
              <div class="form-list-line-right">
                <el-radio-group v-model="timeoption.end" v-if="time_type==1" @change="getTimeFn">
                  <el-radio :label="item.id" v-for="item in timeType" :key="item.id">{{ item.name }}</el-radio>
                </el-radio-group>
                <el-time-picker
                    class="w-80"
                    v-else
                    size="small"
                    v-model="end_hours"
                    @change="typeChangeFn()"
                    format="HH:mm"
                    value-format="HH:mm"
                    :picker-options="{
    selectableRange: '06:00:00 - 23:00:00'
  }"
                    placeholder="选择时间">
                </el-time-picker>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="审批人：" prop="num">
            <el-select v-model="infoForm.examine_user" placeholder="请选择" size="small">
              <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.realname"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="`时长(${time_type==1?'天':'小时'})：`" prop="num">
            {{ infoForm.day }}
          </el-form-item>
          <el-form-item label="抄送人:">
            <div class="user-list">
              <el-button type="primary" @click="getUserList()" size="small"><i class="el-icon-plus"></i>选择抄送人（可不选）
              </el-button>
            </div>
            <div>
              <el-tag
                  :key="tag.id"
                  v-for="(tag,index) in dynamicTags"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(index)"
                  class="mr-10"
              >{{ tag.realname }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item label="请假事由：" prop="num">
            <el-input v-model="infoForm.content" placeholder="备注" size="small"></el-input>
          </el-form-item>
          <div class="file-get-box">
            <el-divider>附件</el-divider>
            <div v-for="(item, index) in fileList" :key="index" class="file-get-body">
              <p class="file-get-list">
                {{ index + 1 }}.
                <btn_file :option="item"></btn_file>
              </p>
              <span class="deteilSpan" @click="deteleFn(index)">删除</span>
            </div>
            <uploadFileModle number="20" @getFile="getFile" ref="uploadFileModle" :sycnStatus="true"
                             fileType="interaction_add" :showfile="false" :fileListPush="getList"></uploadFileModle>
          </div>
        </el-form>

      </div>
      <div class="cornerComment-in-footer">
        <el-button @click.native="closePOpup" size="small">取消</el-button>
        <el-button size="small" type="primary" @click="checkEditFn
">确定并提交</el-button>
      </div>
    </div>
    <MultipleTeacherModle :visible.sync="teacherVisible" @studentFn="studentFn"
                          :dynamicTagsArray="dynamicTagsArray"></MultipleTeacherModle>
  </div>
</template>

<script>
import {typeIndex, leaveAdd} from '@/api/admin/staffService'
import {holidayNow} from '@/api/admin/setting'

export default {
  props: ['visible'], // recruitmentType examine 审核
  components: {},
  data() {
    return {
      teacherVisible: false,
      dialogVisible: this.visible,
      infoForm: {
        cate_id: '',// 	整型 	必填 	1 	- 	类型
        start_time: '',// 	整型 	必填 	1 	- 	开始时间
        end_time: '',// 	整型 	必填 	1 	- 	结束时间
        day: 0,// 	整型 	必填 	1 	- 	天数
        content: '',// 	整型 	必填 	1 	- 	原因
        examine_user: '',
        read_user: '' // 抄送人
      },
      tabList: [],
      options: [],
      user_id: '',
      fileList: [],
      getList: [],
      timeType: [
        {
          id: 1,
          name: '上午'
        },
        {
          id: 2,
          name: '下午'
        }
      ],
      timeoption: {
        start: 1,
        end: 1
      },
      start_hours: '',
      end_hours: '',
      activeDay: [],
      loadingFrom: false,
      time_type: 0,
      dynamicTags: [],
      dynamicTagsArray: {},
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        this.InitFn()
        this.holidayNowFn()
      }
    }
  },
  created() {

  },
  methods: {
    getUserList(){
      let list = {};
      for (let item of this.dynamicTags) {
        list[item.id] = item
      }
      this.dynamicTagsArray = JSON.parse(JSON.stringify(list))
      this.teacherVisible = true
    },
    handleClose(index) {
      this.dynamicTags.splice(index, 1)
    },
    holidayNowFn() {
      holidayNow().then(res => {
        console.log('当前设置：', res)
        this.activeDay = res.detail.holiday.split(',')
      })
    },
    getFile(option) {
      console.log('收到附件数据：', option)
      this.getList = this.getJson(option)
      let url_ = []
      for (let item of this.fileList) {
        url_.push(item.src)
      }
      if (option) {
        for (let item of option) {
          if (url_.indexOf(item.src) === -1) {
            this.fileList.push({
              name: item.name,
              src: item.src
            })
          }
        }
      }
    },
    deteleFn(index) {
      let src_ = this.fileList[index].src
      console.log('this.getList:', this.getList)
      if (this.getList.length) {
        let index_ = 0
        for (let i in this.getList) {
          let item = this.getList[i]
          if (item.src === src_) {
            index_ = i
          }
        }
        console.log('index_,', index_)
        this.getList.splice(index_, 1)
        console.log(this.getList)
      }
      this.fileList.splice(index, 1)
    },
    studentFn(option) {
      console.log('option:', option)
      this.dynamicTags = []
      let list = [];
      for (let i in option) {
        list.push(option[i])
      }
      this.dynamicTags = JSON.parse(JSON.stringify(list))
    },
    checkEditFn() {
      console.log(this.infoForm)
      let data_ = this.getJson(this.infoForm)
      if (!this.infoForm.start_time) {
        this.$message.error('选择请假开始时间')
        return
      }
      if (!this.infoForm.end_time) {
        this.$message.error('选择请假结束时间')
        return
      }
      if (!this.infoForm.examine_user) {
        this.$message.error('选择审核人')
        return
      }
      if (!this.infoForm.day) {
        this.$message.error('未计算时长，请正确填写开始时间，结束时间！')
        return
      }
      // data_.start_time = data_.start_time + ' 00:00:00'
      // data_.end_time = data_.end_time + ' 23:59:59'
      if (this.time_type===2) {
        data_.start_time = `${data_.start_time} ${this.start_hours}:00`
        data_.end_time = `${data_.end_time} ${this.end_hours}:00`
      } else {
        let start_time = data_.start_time
        let end_time = data_.end_time
        if (this.timeoption.start === 1) {
          start_time = start_time + ' 7:30:00'
        } else {
          start_time = start_time + ' 12:00:00'
        }
        if (this.timeoption.end === 1) {
          end_time = end_time + ' 12:00:00'
        } else {
          end_time = end_time + ' 17:30:00'
        }
        data_.start_time = start_time
        data_.end_time = end_time
      }
      if(this.dynamicTags.length){
        let a_ = []
        for(let item of this.dynamicTags){
          a_.push(item.id)
        }
        data_.read_user = a_.join(',')
      }
      data_.file = JSON.stringify(this.fileList)
      console.log('data_:', data_)
      leaveAdd(data_).then(res => {
        console.log('res:', res)
        if (!res.code) {
          this.$message.success(res.msg)
          this.$emit('InitFn')
          this.closePOpup()
        } else {
          this.$message.error(res.msg)
        }
      })

      // if (!this.infoForm[this.itemlable]) {
      //   this.$message.error('请填写信息');
      //   return
      // }
      // this.$emit('checkList', {name: this.itemlable, val: this.infoForm[this.itemlable]})
      // this.closePOpup()
    },
    getTimeFn() {
      console.log('校园假期：', this.activeDay)
      console.log('小时：', this.start_hours, this.end_hours)
      let state = false
      if (this.infoForm.end_time && this.infoForm.start_time) {
        if (this.time_type===2 && this.start_hours && this.end_hours) {
          state = true
        }
        if (this.time_type===1) {
          state = true
        }
      }
      if (!state) {
        return
      }
      let start = this.infoForm.start_time;
      let end = this.infoForm.end_time;
      let format = (time) => {
        let ymd = ''
        let mouth = (time.getMonth() + 1)
        let day = time.getDate() >= 10 ? time.getDate() : ('0' + time.getDate());
        ymd += time.getFullYear() + '-' // 获取年份。
        ymd += mouth + '-' // 获取月份。
        ymd += day // 获取日。
        //m.df格式
        return ymd // 返回日期。
      }
      let dateArr = []
      let startArr = start.split('-')
      let endArr = end.split('-')
      let db = new Date()
      db.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2])
      db.setHours(0, 0, 0, 0)
      let de = new Date()
      de.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2])
      de.setHours(0, 0, 0, 0)
      let unixDb = db.getTime()
      let unixDe = de.getTime()
      let stamp
      let oneDay = 24 * 60 * 60 * 1000;
      for (stamp = unixDb; stamp <= unixDe;) {
        let f = new Date(parseInt(stamp));
        dateArr.push(format(f))
        stamp = stamp + oneDay
      }
      // this.allDay = JSON.parse(JSON.stringify(dateArr))
      // 比对时间内容
      let newList = []
      for (let item of dateArr) {
        if (this.activeDay.indexOf(item) === -1) {
          newList.push(item)
        }
      }
      console.log('可以请假的时间：', newList)
      if (this.time_type===2) {
        let startTime = new Date(`${this.infoForm.start_time} ${this.start_hours}:00`).getTime();
        let endTime = new Date(`${this.infoForm.end_time} ${this.end_hours}:00`).getTime();
        // this.infoForm.day = startTime === endTime ? 1 : (Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24)) + 1;
        let ms = endTime - startTime;
        let met_ = Math.floor(ms / 1000 / 60)
        if (ms < 0) return 0;
        console.log('计算小时：', met_)
        console.log('计算小时：', parseInt(met_ / 60), met_ % 60)
        if (met_ <= 60) {
          console.log('请假时长：', 1)
          this.infoForm.day = 1
        } else {
          let t_ = parseInt(met_ / 60)
          if (met_ % 60) {
            t_ = t_ + 1
          }
          console.log('请假时长：', t_)
          this.infoForm.day = t_
        }
        // this.infoForm.day = Math.floor(ms / 1000 / 60 / 60);
      } else {
        let dayNumber = newList.length
        if (newList.indexOf(start) !== -1) {
          if (this.timeoption.start === 2) {
            dayNumber = dayNumber - 0.5
          }
        }
        if (newList.indexOf(end) !== -1) {
          if (this.timeoption.end === 1) {
            dayNumber = dayNumber - 0.5
          }
        }
        this.infoForm.day = dayNumber
      }
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    // 初始化
    InitFn() {
      typeIndex({p: 1}).then(res => {
        this.tabList = res.list.data;
        if (res.list.data.length) {
          this.infoForm.cate_id = res.list.data[0].id
          this.time_type =  res.list.data[0].time_type
          this.options = this.getJson(res.list.data[0].user_ids)
        }
        this.loadingFrom = true
      })
    },
    changeTime(){
      this.infoForm.examine_user = ''
      for(let item of this.tabList){
        if(item.id === this.infoForm.cate_id){
          this.time_type =  item.time_type
          this.options = this.getJson(item.user_ids)
        }
      }
    },
    typeChangeFn() {
      console.log(this.infoForm.cate_id)
      for (let item of this.tabList) {
        if (item.id === this.infoForm.cate_id) {
          this.options = this.getJson(item.user_ids)
        }
      }
      if (this.time_type === 1) {
        this.start_hours = ''
        this.end_hours = ''
      }
      if (this.infoForm.end_time && this.infoForm.start_time) {
        this.getTimeFn()
      }
    }
  },
  mounted() {
  }
}
</script>
<style scoped>
#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 650px;
  height: 600px;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  padding: 0px;
  flex: 1;
  overflow-y: auto;
}

.close-Btn-line {
  cursor: pointer;
}

.resruitment-title {
  padding: 5px 0;
  border-bottom: 2px solid #abd3f3;
  margin-bottom: 20px;
}

.el-radio {
  margin-right: 20px;
}

.jobTime {
  display: flex;
  align-items: center;
}

.jobTime span {
  padding: 0 10px;
}

.file-get-list {
  display: flex;
  padding: 5px;
  background: #eee;
  border-radius: 4px;
  align-items: center;
  flex: 1;
}

.file-get-body {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.deteilSpan {
  padding: 0 10px;
  font-size: 12px;
}

.form-box {
  padding-right: 20px;
  padding-bottom: 40px;
}

.form-list-line {
  display: flex;
  align-items: center;
}

.form-list-line .w-100 {
  width: 160px !important;
}

.form-list-line .w-80 {
  width: 100% !important;
}

.form-list-line-right {
  flex: 1;
}

.file-get-box {
  padding-left: 20px;
}
</style>


